import React from 'react';
import { inject, observer } from 'mobx-react';
import { Modal, message, Button, Tooltip } from 'antd';
import { WeaDialog, WeaInput, WeaTextarea, WeaNewScroll, WeaInputNumber, WeaDatePicker, WeaFormItem, WeaTableEditable, WeaRichText, WeaTable, WeaBrowser, WeaLocaleProvider, WeaSearchGroup } from 'ecCom';
import PlanDetail from './planDetail'
import * as Util from '../../../util/Util.js';
import FeedBack from '../../../public/feedback/FeedBack';
import CubeLayout from "../../../../govern/components/E9/cubeLayout";
import Feedback from './feedback'
const toJS = mobx.toJS;
const confirm = Modal.confirm
const getLabel = WeaLocaleProvider.getLabel;
@inject('planViewStore')
@observer
export default class PlanAndSummary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            _height: Util.getCurrentHeight(),
            planDetailVisible: false,
            editDialogVisible: false,
            editDiaLogButtons: [],
            editValue: { //新建编辑框的值
                id: 'temp+' + new Date().getTime(),
            },
            editInitValue: {},
            editType: 'summary',
            currentPointerRowSummaryType: 'in', //当前鼠标悬浮行是计划内还是外
            detailId: '',
            dataType: '', //2或者3 标识计划还是总结
            inOrOut: 'in', //当前点击的是计划内还是外还是计划
            summaryVisible: true,
            planVisible: true,
            remarkVisible: true,
            relateVisible: true,
            feedbackVisible: true,
        };
        this.store = this.props.planViewStore;
    }
    componentWillMount() {
    }

    render() {
        const { isshowsummary, isshowplan, loading, resourcename, year, type1, type2, summaryInCantEditFields, planstatus, resourceid, remark, category, canedit, summaryColumns, summaryTableData, summarymap, planColumns, planlist, alinks, tabSelectKey, isperformance, cubeLayoutParame, getCardStorefun, iscube } = this.store
        const { summaryVisible, planVisible, remarkVisible, relateVisible, inOrOut, _height, dataType, detailId, planDetailVisible, editDialogVisible, editType, editDiaLogButtons, editValue, currentPointerRowSummaryType } = this.state
        let toJSSummaryColumns = toJS(summaryColumns)
        let toJSPlanColumns = toJS(planColumns)
        this.addOperationColumns(toJSSummaryColumns, currentPointerRowSummaryType);
        this.addOperationColumns(toJSPlanColumns, 'plan');
        let cubeFlag = Object.keys(toJS(cubeLayoutParame)).length > 0;
        //启用建模
        if (iscube == '1' && cubeFlag) {
            return <div>
                {CubeLayout({ cubeLayoutParame, "getEcmeFieldData": this.getEcmeFieldData, "callback": this.ecmeCallBack, "ecmeFieldEventCallBack": this.ecmeFieldEventCallBack, getCardStorefun })}
                {!loading && this.relatedLinks()}
                {!loading && !canedit && this.buildFeedback()}
            </div>

        }

        return (
            <div className="plan-summary">
                {/* 上月总结 */}
                {isshowsummary != '0' && <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wx6oe2`} title={<span><i
                    className="icon-coms-mulujibenxinxi"
                    style={{ color: 'green' }}
                /> {this.getSearchGroupTitle()}</span>}
                    showGroup={summaryVisible}
                    onVisibleChange={(e) => { this.setState({ summaryVisible: e }) }}
                >
                    <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@syitv3`}
                        // showTitle={true}
                        showCopy={false}
                        draggable={false}
                        pushTitleIntoHeader={false}
                        columns={toJSSummaryColumns}
                        buttonsType="inline"
                        datas={summaryTableData}
                        willAdd={this.summaryWillAdd}
                        willDelete={this.summaryWillDelete}
                        tableProps={this.getSummaryTableProps()}
                        showAdd={this.canEditPlan()}
                        showDelete={this.canEditPlan()}
                        getRowSelection={rowSelection => {
                            const sel = { ...rowSelection };
                            sel.getCheckboxProps = record => {
                                return { disabled: record.planType == "计划内" };
                            };
                            return canedit ? sel : null;
                        }}
                    />
                </WeaSearchGroup>
                }
                {/* 本月计划 */}
                {isshowplan != '0' &&
                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@up8m5v`} title={<span><i
                        className="icon-coms-mulujibenxinxi"
                        style={{ color: 'red' }}
                    /> {this.getPlanSearchGroupTitle()}</span>}
                        showGroup={planVisible}
                        onVisibleChange={(e) => { this.setState({ planVisible: e }) }}
                    >
                        <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@rfj1uq`}
                            // showTitle={true}
                            showCopy={false}
                            draggable={false}
                            pushTitleIntoHeader={false}
                            columns={toJSPlanColumns}
                            buttonsType="inline"
                            datas={toJS(planlist)}
                            willAdd={this.planWillAdd}
                            willDelete={this.planWillDelete}
                            tableProps={this.getPlanTableProps()}
                            showAdd={this.canEditPlan()}
                            showDelete={this.canEditPlan()}
                            getRowSelection={rowSelection => {
                                const sel = { ...rowSelection };

                                return canedit ? sel : null;
                            }}
                        />
                    </WeaSearchGroup>
                }
                {/* 说明 */}

                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@4t7rn4`}
                    title={getLabel('25734', '说明')}
                    showGroup={remarkVisible}
                    onVisibleChange={(e) => { this.setState({ remarkVisible: e }) }}
                    className="search-group"
                >

                    {this.canEditPlan()
                        ? <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@9t4ska`}
                            ckConfig={{
                                startupFocus: false,
                                toolbar: [
                                    { name: 'document', items: ['Source'] },
                                    { name: 'clipboard', items: ['Undo', 'Redo'] },
                                    { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList'] },
                                    { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
                                    { name: 'colors', items: ['TextColor'] },
                                    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike',] },
                                    { name: 'insert', items: ['Image', 'Flash', 'Table', 'Smiley'] },
                                    { name: 'tools', items: ['Maximize'] },
                                ],
                                height: 200,
                                autoGrow_minHeight: 200,
                                autoGrow_maxHeight: 200,
                                uploadUrl: '/api/doc/upload/uploadFile',
                                resize_enabled: false,
                            }}
                            value={remark}
                            // extentsConfig
                            onChange={v => this.richTextChange(v)}
                            onToolsChange={(name, ids, list, type) =>
                                Util.transfStr(name, ids, list, type)}
                        />
                        : (remark ? <div className="wea-workrelate-remark-number"
                            style={{ padding: '10px' }}
                            dangerouslySetInnerHTML={{ __html: remark }}
                        /> : <div className="nodata" style={{ marginLeft: '2opx', textAlign: 'left' }}>{getLabel(84304, "暂无")}</div>)}

                </WeaSearchGroup>

                {(tabSelectKey == 1 || (alinks.length > 0 && tabSelectKey == '2')) && this.relatedLinks()
                }
                {!loading && !canedit &&this.buildFeedback()}


                {/* 计划详情 */}
                {planDetailVisible && <PlanDetail ecId={`${this && this.props && this.props.ecId || ''}_PlanDetail@ke5enz`}
                    detailid={detailId} //detailid
                    datatype={dataType}//数据类型
                    canedit={canedit}//是否能编辑
                    resourceid={resourceid} //人员id
                    onClose={this.closeDia}
                    type={'report'}
                    planstatus={planstatus}
                    visible={planDetailVisible}
                    inOrOut={inOrOut}
                    summaryInCantEditFields={summaryInCantEditFields}
                ></PlanDetail>}
                {/* 新建和编辑框 */}
                {editDialogVisible && <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@laou1z`}
                    title={editType == 'summary' ? getLabel('509021', '总结') : getLabel('18170', '工作计划')}
                    icon={'icon-coms-implement'}
                    iconBgcolor={'rgb(150, 53, 138)'}
                    visible={editDialogVisible}
                    buttons={editDiaLogButtons}
                    onCancel={() => this.setState({ editDialogVisible: false })}
                    hasScroll={true}
                    children={
                        <div >
                            <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@0wd1wi`} showGroup={true}>
                                {this.getEditModalColumns().map((v, i) => {
                                    return this.getFormItem(
                                        v.inputtype,
                                        v.showname,
                                        editValue[v.fieldname],
                                        canedit ? '2' : '1',
                                        v.fieldname,
                                        v.ismust,
                                        v.ismust2
                                    );
                                })}
                            </WeaSearchGroup>
                        </div>
                    }
                />}
            </div>
        );
    }

    richTextChange = v => {
        this.store.setValue("remark", v)
    };
    getSearchGroupTitle = () => {
        let { userLanguage, year, type1, type2 } = this.store
        let borderMonthTitle = userLanguage == 8 ?
            `${year}-${type2} work summary`
            :
            `${year}${getLabel('26577', '年')}${type2}${getLabel('509037', '月工作总结')} `

        let borderWeekTitle = userLanguage == 8 ?
            `${year} Week ${type2} work summary`
            :
            `${year}${getLabel('26577', '年')}${type2}${getLabel('509038', '周工作总结')} `
        return type1 == 1 ? borderMonthTitle : borderWeekTitle

    }
    getPlanSearchGroupTitle = () => {

        let { year, type1, type2, userLanguage } = this.store
        if (type1 == 1) {
            let showYear = type2 == 12 ? parseInt(year) + 1 : year;
            let showMonth = type2 == 12 ? 1 : parseInt(type2) + 1;
            return userLanguage == 8 ?
                `${showYear}-${showMonth} work plan`
                :
                `${showYear}${getLabel('26577', '年')}${showMonth}${getLabel('18136', '月工作计划')} `
        } else {
            let showYear = (parseInt(type2) == 53 || parseInt(type2) == 52) ? parseInt(year) + 1 : year
            let showWeek = (parseInt(type2) == 53 || parseInt(type2) == 52) ? 1 : parseInt(type2) + 1
            return userLanguage == 8 ? `${showYear} Week ${showWeek} work plan`
                :
                `${showYear}${getLabel('26577', '年')}${showWeek}${getLabel('30842', '周工作计划')} `
        }


    }

    buildEditModalButtons = (isEdit, index) => {
        let { editType, editValue, currentPointerRowSummaryType } = this.state
        const { summaryoutIds, summaryinIds, planIds, summaryout, planlist } = this.store
        this.setState({ editInitValue: toJS(editValue) })
        editValue['planType'] = editType == 'summary' ? (currentPointerRowSummaryType == 'in' ? '计划内' : "计划外") : ''
        let buttons = [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j4lcbs@sure`} type="primary" onClick={() => {
                if (!this.checkMust()) {
                    message.info(getLabel('509065', '请输入必填项'));
                    return
                }
                if (!isEdit) {
                    editType == 'summary' ?
                        this.store.addSummaryOut(editValue, index)
                        :
                        this.store.addPlanList(editValue, index)
                } else {
                    let summaryIndex = summaryoutIds.indexOf(editValue.id)
                    let planIndex = planIds.indexOf(editValue.id)
                    let summaryinIndex = summaryinIds.indexOf(editValue.id)
                    if (summaryinIndex > -1) {
                        this.store.summaryInChange(editValue, summaryinIndex)
                    }
                    if (summaryIndex > -1) {
                        this.store.summaryOutChange(editValue, summaryIndex)
                    }
                    if (planIndex > -1) {
                        this.store.planListChange(editValue, planIndex)
                    }
                }
                this.setState({ editDialogVisible: false })

            }}>{getLabel('826', '确定')}</Button>,
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lj2lc5@cancle`} type="ghost" onClick={() => {
                this.setState({ editDialogVisible: false })
            }}>{getLabel('31129', '取消')}</Button>
        ];
        this.setState({ editDiaLogButtons: buttons })
    }

    summaryWillAdd = (datas, addData) => {
        datas.pop();
        this.setState({
            editType: 'summary',
            currentPointerRowSummaryType: 'out',
            editDialogVisible: true, editValue: {
                id: 'temp+' + new Date().getTime(),
            }
        }, () => {
            this.buildEditModalButtons()
        })
        return datas;
    };
    planWillAdd = (datas, addData) => {
        datas.pop();

        this.setState({
            editType: 'plan',
            editDialogVisible: true, editValue: {
                id: 'temp+' + new Date().getTime(),
            }
        }, () => {
            this.buildEditModalButtons()
        })
        return datas;
    };
    summaryWillDelete = (datas, keys) => {
        const { summaryinIds } = this.store
        this.store.setValue('summaryout', datas.filter(v => { return summaryinIds.indexOf(v.id) == -1 }))
        return true;
    };
    planWillDelete = (datas, keys) => {
        this.store.setValue('planlist', datas)
        return true;
    };

    getFormItem = (type, label, value, viewAttr, fieldname, ismust, ismust2) => {
        const { summaryInCantEditFields } = this.store
        const { currentPointerRowSummaryType, editValue, editType } = this.state
        //如果是标题必填
        if (fieldname == 'name') {
            viewAttr = 3
        }
        //编辑计划内， 计划包含的字段不可编辑
        if (editType != 'plan' && currentPointerRowSummaryType == 'in' && summaryInCantEditFields.indexOf(fieldname) > -1) {
            viewAttr = 1
        }
        //新建的都可以编辑
        if (editValue.id && editValue.id.indexOf("temp") > -1) {
            viewAttr = 2
        }
        //如果必填
        if (viewAttr == 2 && (ismust == 1 || ismust2 == 1)) {
            viewAttr = 3;
        }
        return (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@cns7zj`}
                label={label}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
            >

                {type == 1 &&
                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@xas62p`}
                        value={value}
                        viewAttr={viewAttr}
                        onChange={e => this.onEditInputChange(fieldname, e)}
                    />}
                {type == 2 &&
                    <WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@sgpdnr`}
                        viewAttr={viewAttr}
                        value={value && value.replace(/<br\/>/g, "\n")}
                        onChange={e => this.onEditInputChange(fieldname, e)}
                    />}
                {type == 3 &&
                    <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@sr6bgm`}
                        value={value}
                        viewAttr={viewAttr}
                        onChange={e => this.onEditInputChange(fieldname, e)}
                    />}
                {type == 4 &&
                    <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@91humc`}
                        viewAttr={viewAttr}
                        value={value}
                        onChange={e => this.onEditInputChange(fieldname, e)}
                    />}

            </WeaFormItem>
        );
    };
    //获取编辑modal的表单
    getEditModalColumns = () => {
        const { editType } = this.state
        const { planmap, summarymap } = this.store
        return editType == 'plan' ? (planmap.list ? planmap.list : []) : (summarymap.list ? summarymap.list : [])
    }
    //编辑表单里的change事件
    onEditInputChange = (fieldname, e) => {
        let { editValue } = this.state;

        let col, tip = ''; //被改变的值
        let days = 0;
        let flag = true;
        if (
            fieldname == 'begindate2' &&
            editValue['enddate2'] &&
            editValue['enddate2'] != ''
        ) {
            days = Util.DateDiffDays(e, editValue['enddate2']);
            if (days < 0) {
                flag = false;
                tip = getLabel('509026', '实际开始日期不能大于实际结束日期!');
            } else {
                col = 'days2';
            }
        } else if (
            fieldname == 'enddate2' &&
            editValue['begindate2'] &&
            editValue['begindate2'] != ''
        ) {
            days = Util.DateDiffDays(editValue['begindate2'], e);
            if (days < 0) {
                flag = false;
                tip = getLabel('509027', '实际结束日期不能小于实际开始日期!');
            } else {
                col = 'days2';
            }
        } else if (
            fieldname == 'begindate1' &&
            editValue['enddate1'] &&
            editValue['enddate1'] != ''
        ) {
            days = Util.DateDiffDays(e, editValue['enddate1']);
            if (days < 0) {
                flag = false;
                tip = getLabel('509028', '计划开始日期不能大于计划结束日期!');
            } else {
                col = 'days1';
            }
        } else if (
            fieldname == 'enddate1' &&
            editValue['begindate1'] &&
            editValue['begindate1'] != ''
        ) {
            days = Util.DateDiffDays(editValue['begindate1'], e);
            if (days < 0) {
                flag = false;
                tip = getLabel('509029', '计划结束日期不能小于计划开始日期!');
            } else {
                col = 'days1';
            }
        }
        if (col != '') {
            editValue[col] = days ? days : 0;
            editValue["s_" + col] = days ? days : 0;
        }
        if (flag) {
            if ((fieldname == 'days1' || fieldname == 'days2') && !e) {
                editValue[fieldname] = ''
                editValue["s_" + fieldname] = ''
            } else {
                editValue[fieldname] = e;
                editValue["s_" + fieldname] = typeof (e) == 'string' ? e.replace(/\n/g, "<br/>") : e;
            }
            this.setState({ editValue });
        } else {
            message.info(tip);
            this.setState({ editValue });
        }
    };
    //检查必填项
    checkMust = () => {
        let { editValue, editType } = this.state;
        var flag = true;
        let { summarymap, planmap } = this.store;
        let checkMap = editType == 'summary' ? summarymap.list : planmap.list
        for (var v in editValue) {
            checkMap.map(p => {

                if (p['ismust'] == 1 && (editValue[p['fieldname']] === '' || editValue[p['fieldname']] == undefined)) {
                    flag = false;
                }
                if (!editValue['name'] || editValue['name'] == undefined || editValue['name'] == '') {
                    flag = false;
                }
            });
        }
        return flag;
    };
    //第二个参数是类型 type in 是 计划内 out 计划外
    addOperationColumns = (columns, type) => {
        columns.push({
            title: <span />,
            dataIndex: 'customrender',
            width: '0',
            key: 'customrender',
            com: [
                {
                    type: 'CUSTOM',
                    key: 'customrender',
                },
            ],
            render: (text, record, index, onEdit) => (
                <div className="operation-col">
                    <div className='icon-context'>
                        {this.canEditPlan() && type != 'plan' && this.store.isshowplan !="0" &&
                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@okqhhu@${index}`} title={getLabel('509024', '添加到工作计划')}>
                                <span>
                                    <i
                                        className="icon-coms-down"
                                        onClick={e => {
                                            e.stopPropagation();
                                            this.addToPlanList(toJS(record));
                                        }}
                                    />{' '}
                                </span>
                            </Tooltip>}
                        {this.canEditPlan() &&
                            (type == 'out' || type == 'plan') &&
                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@rxkeaq@${index}`} title={getLabel('509025', '新增一行数据')}>
                                <span>
                                    <i
                                        className="icon-coms-Left"
                                        onClick={e => {
                                            e.stopPropagation();
                                            this.openAdd(index, type);
                                        }}
                                    />{' '}
                                </span>
                            </Tooltip>}
                        {this.store.createtask && this.store.canedit && 
                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@7xbvwi@${index}`} title={getLabel('16336', '创建任务')}>
                                <span>
                                    <i
                                        className="icon-coms-plus"
                                        onClick={e =>
                                            this.createTask(
                                                e,
                                                text,
                                                record,
                                                index,
                                                onEdit,
                                                type == 'plan' ? "2" : '3',
                                                type
                                            )}
                                    />
                                    {' '}
                                </span>
                            </Tooltip>}
                        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@m0pplk@${index}`} title={getLabel('382624', '查看明细')}>
                            <span>
                                <i
                                    className="icon-coms-form-copy"
                                    onClick={e =>
                                        this.viewDetail(
                                            e,
                                            text,
                                            record,
                                            index,
                                            onEdit,
                                            type == 'plan' ? "2" : '3',
                                            type
                                        )}
                                />
                                {' '}
                            </span>
                        </Tooltip>
                    </div>
                </div>
            ),
        });
    };
    //创建任务
    createTask(e, text, record, index, onEdit, dataType, inOrOut) {
        e.stopPropagation();
        if (record.name == undefined || record.name.length == 0) {
            Modal.warning({
                title: getLabel('558', '提示'),
                content: getLabel('509022', '请填写标题!'),
            });
            return;
        }
        let _this = this;
        let { resourceid, summaryin, summaryout } = this.store;
        let begindate, enddate
        if (inOrOut != 'plan') {
            begindate = record.begindate2
            enddate = record.enddate2
        } else {
            begindate = record.begindate1
            enddate = record.enddate1
        }
        let param = {};
        param.taskName = record.name;
        param.principalid = resourceid;
        param.begindate = begindate
        param.enddate = enddate
        delete record.fbdate;
        if (record.id.indexOf('temp') != -1) {
            record.id = '';
        }
        let toJSRecord = toJS(record)
        delete toJSRecord.planType
        let detailData = '[' + JSON.stringify(toJSRecord) + ']';
        if (record.id == '') {
            //先保存 再查看
            _this.store.saveDetailView({
                operation: 'save_detail',
                resourceid: resourceid,
                plandetailid: record.id,
                dataType: dataType,
                detailData: detailData,
                type1: _this.store.tabSelectKey,

                //保存成功后回调
                doback: function (detailid) {
                    //设置id 
                    record.id = detailid
                    if (inOrOut == 'plan') {
                        _this.store.planlist[index].id = detailid
                    }
                    param.plandetailid = detailid;
                    _this.store.addTask(param, inOrOut == 'in' ? summaryin[index] : summaryout[index]);
                },
            });
        } else {
            param.plandetailid = record.id;
            _this.store.addTask(param, inOrOut == 'in' ? summaryin[index] : summaryout[index]);

        }
    }
    openAdd = (index, type) => {

        this.setState({
            editType: type == 'plan' ? 'plan' : 'summary',
            editValue: {
                id: 'temp+' + new Date().getTime(),
            },
            editDialogVisible: true
        }, () => {
            this.buildEditModalButtons(false, index)
        })
    }
    canEditPlan = () => {
        return this.store.canedit;
    };
    getSummaryTableProps = () => {
        const { summarymap, summaryinIds, summaryoutIds, currentPointerRowSummaryType } = this.store

        let _this = this;
        let columns = toJS(this.store.summaryinColumns)
        let tableProps = {
            onRowClick: (row, index) => {
                if (_this.canEditPlan()) {
                    if (summaryoutIds.indexOf(row.id) > -1) {
                        this.setState({ currentPointerRowSummaryType: 'out', editType: 'summary', editValue: toJS(row), editDialogVisible: true }, () => {
                            this.buildEditModalButtons(true)
                        })
                    }
                    if (summaryinIds.indexOf(row.id) > -1) {
                        this.setState({ currentPointerRowSummaryType: 'in', editType: 'summary', editValue: toJS(row), editDialogVisible: true }, () => {
                            this.buildEditModalButtons(true)
                        })
                    }

                }
            },
            onRowMouseEnter: (id) => {
                if (summaryinIds.indexOf(id) > -1) {
                    this.setState({ currentPointerRowSummaryType: 'in' })
                } else {
                    this.setState({ currentPointerRowSummaryType: 'out' })
                }
            },
            onRowMouseLeave: (...arg) => { }
        }
        tableProps.scroll = { x: summarymap.totalwidth + '%' }

        return tableProps;
    };
    getPlanTableProps = () => {
        const { planColumns, planIds, planmap } = this.store

        let _this = this;
        let columns = toJS(planColumns)
        let tableProps = {
            onRowClick: (row, index) => {
                if (_this.canEditPlan()) {
                    if (planIds.indexOf(row.id) > -1) {
                        this.setState({ editType: 'plan', editValue: toJS(row), editDialogVisible: true }, () => {
                            this.buildEditModalButtons(true)
                        })
                    }
                }
            },
            onRowMouseEnter: (id) => {
            },
            onRowMouseLeave: (...arg) => { }
        }
        tableProps.scroll = { x: planmap.totalwidth + '%' }

        return tableProps;
    };
    getModalHeight = (_height, columns) => {
        let h = _height * 0.6
        if (columns && columns.length > 0) {
            let itemCountHeight = columns.length * 50 + 50
            if (itemCountHeight > h) {
                return h
            } else {
                return itemCountHeight
            }

        } else {
            return h
        }

    }
    addToPlanList = record => {
        record.id = 'temp' + new Date().getTime();
        let { planlist } = this.store
        planlist.push(record)
        this.store.setValue('planlist', planlist)
        message.success(getLabel('30700', '操作成功'));
    };
    //查看明细 弹出明细弹窗
    viewDetail(e, text, record, index, onEdit, dataType, inOrOut) {
        e.stopPropagation();
        let { canedit, category, resourceid, summaryin, summaryout, planlist, planstatus } = this.store;
        delete record.fbdate;
        if (record.id.indexOf('temp') != -1) {
            record.id = '';
        }
        let _this = this;
        let toJSRecord = toJS(record)
        delete toJSRecord.planType
        delete toJSRecord.undefined
        delete toJSRecord.s_undefined
        let detailData = '[' + JSON.stringify(toJSRecord) + ']';
        //先保存 再查看
        this.store.saveDetailView({
            operation: 'save_detail',
            resourceid: resourceid,
            plandetailid: record.id,
            dataType: dataType,
            detailData: detailData,
            type1: _this.store.tabSelectKey,
            //保存成功后回调
            doback: function (detailId) {
                record.id = detailId
                if (inOrOut == 'plan') {
                    planlist[index] = record
                    _this.store.setValue('planlist', planlist)
                }
                _this.setState({ detailId: detailId, dataType, planDetailVisible: true, inOrOut: inOrOut })
            },
        });
    }
    //回调关闭dialog 关闭后把列表里的内容更新
    closeDia = (params, detailid) => {
        params['viewdate'] = ''
        delete params['viewdate']
        delete params['taskarray']
        delete params['taskids']
        this.setState({ planDetailVisible: false });
        if (params) {
            let { summaryin, summaryout, planlist, summaryinIds, summaryoutIds, planIds } = this.store;
            let thisRow = {}
            let rowIndex = -1


            let summaryInIndex = summaryinIds.indexOf(detailid)
            let summaryOutIndex = summaryoutIds.indexOf(detailid)
            let planIndex = planIds.indexOf(detailid)

            if (summaryInIndex > -1) {
                thisRow = toJS(summaryin[summaryInIndex])
                rowIndex = summaryInIndex
            }
            if (summaryOutIndex > -1) {
                thisRow = toJS(summaryout[summaryOutIndex])
                rowIndex = summaryOutIndex
            }
            if (planIndex > -1) {
                thisRow = toJS(planlist[planIndex])
                rowIndex = planIndex
            }
            for (let k in params) {
                if (k && !k.startsWith("s_")) {
                    if (params[k]) {
                        thisRow[k] = params[k]
                        if (!k.startsWith("s_")) {
                            thisRow["s_" + k] = typeof (thisRow[k]) == 'string' ? thisRow[k].replace(/\n/g, "<br/>") : thisRow[k]
                        }
                    } else {
                        thisRow[k] = ''
                        if (!k.startsWith("s_")) {
                            thisRow["s_" + k] = ''
                        }
                    }
                }
            }
            thisRow["id"] = detailid
            if (summaryInIndex > -1) {
                summaryin[summaryInIndex] = thisRow

            }
            if (summaryOutIndex > -1) {
                summaryout[summaryOutIndex] = thisRow
            }
            if (planIndex > -1) {
                planlist[planIndex] = thisRow
            }
        }
    };

    getEcmeFieldData = (path, param) => {
        return null;
    }

    ecmeCallBack = () => {
        const { planid, summaryinIds, summaryTableData, summaryInCantEditFields, Card } = this.store
        this.store.setValue("cubeLoading", false)
        const { allFields } = Card
        if (planid == '') {
            this.store.dealInitData()
        }
        //计划内数据不许选中
        summaryTableData.forEach((v, i) => {
            if (summaryinIds.indexOf(v.id) > -1) {
                window.ModeForm.controlDetailRowDisableCheck('detail_1', i + "", true)
            }
        })
        //计划有的属性计划内不可编辑
        let detailDataMap = {}
        for (var k in allFields) {
            if (allFields[k].detail == 'detail_1') {
                if (summaryInCantEditFields.indexOf(allFields[k].fieldname) > -1) {
                    detailDataMap[allFields[k].fieldname] = k
                }
            }
        }
        summaryTableData.forEach((v, i) => {
            if (summaryinIds.indexOf(v.id) > -1) {
                for (var k in detailDataMap) {
                    window.ModeForm.changeSingleField(detailDataMap[k] + '_' + i, {}, { viewAttr: "1" })
                }
            }
        })

    }
    //type-onChange onblur onfoncus fieldname-更改的字段 tablename-更改的表名 fieldhtmltype-更改字段类型 newvalue-更改后的值 rowIndex-明细表主键id
    ecmeFieldEventCallBack = (datas) => {
        let type = datas.changetype;
        let fieldInfo = datas.fieldInfo;
        let fieldname = fieldInfo.fieldname;
        let fieldhtmltype = fieldInfo.fieldhtmltype;
        let tablename = fieldInfo.tablename;
        let newvalue = datas.fieldnewvalue;
        let fieldmark = datas.fieldMark;
        let iscustom = datas.iscustom;
        let rowIndex = datas.rowIndex;
        let isCallBack = false;
        this.store.setValue("cubeLoading", false)

    }
    relatedLinks = () => {
        let { relateVisible } = this.state
        let { tabSelectKey, isperformance, resourceid, resourcename, year, type2, alinks } = this.store
        return <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@b61qwo`}
            title={getLabel('24969', '相关链接')}
            showGroup={relateVisible}
            onVisibleChange={(e) => { this.setState({ relateVisible: e }) }}
            className="search-group"
        >

            {tabSelectKey == '1' && isperformance == true &&
                <div className='planview-alink'>
                    <a target='_blank'
                        href={`/spa/workrelate/static/index.html#/main/workrelate/performance/accessView?year=${year}&type1=1&type2=${type2}&resourceid=${resourceid}`}
                        title={`${resourcename}${getLabel('508616', '目标绩效考核')}(${year}-${type2.length < 2 ? "0" + type2 : type2})`}
                    >
                        {`${resourcename}${getLabel('508616', '目标绩效考核')}(${year}-${type2.length < 2 ? "0" + type2 : type2})`}
                    </a>
                </div>
            }

            {(alinks && alinks.length > 0) ? <span>
                {alinks.map(v => {
                    return <div className='planview-alink'><a title={v.linkname} target='_blank' href={v.linkurl}>
                        {v.linkname}
                    </a></div>
                })}
            </span> : ""}

        </WeaSearchGroup>
    }

    buildFeedback = () => {
        let { fblist } = this.store;
        fblist = fblist ? toJS(fblist) : [];
        fblist = this.formatFblist(fblist);
        const { feedbackVisible } = this.state
        return <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@xp7oqn`}
            title={getLabel('33956', '意见反馈')}
            showGroup={feedbackVisible}
            onVisibleChange={(e) => { this.setState({ feedbackVisible: e }) }}
            className="search-group"
        ><div className="plan-feedback">
                <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@5wmdaa`}
                    ckConfig={{
                        startupFocus: false,
                        toolbar: [
                            { name: 'document', items: ['Source'] },
                            { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
                            { name: 'insert', items: ['Table', 'Smiley'] },

                            {
                                name: 'paragraph',
                                items: [
                                    'JustifyLeft',
                                    'JustifyCenter',
                                    'JustifyRight',
                                    '-',
                                    'NumberedList',
                                    'BulletedList',
                                ],
                            },

                            { name: 'colors', items: ['TextColor'] },
                            {
                                name: 'basicstyles',
                                items: ['Bold', 'Italic', 'Underline', 'Strike'],
                            },
                        ],
                        height: 100,
                        autoGrow_minHeight: 100,
                        autoGrow_maxHeight: 200,
                        resize_enabled: false,
                    }}
                    value={this.store.feedback}
                    onChange={v => this.feedbackRichTextChange(v)}
                    bottomBarRight={{
                        width: 100,
                        Component: [
                            <span
                                className="wea-rich-text-toolbar-bottom-item"
                                style={{ position: 'relative' }}
                            >
                                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yxho5o@submit`}
                                    className="wea-button-release"
                                    onClick={this.saveFeedback}
                                >
                                    <span>
                                        <span className="icon-coms-Release" />
                                        <span style={{ marginLeft: '2px' }}>{getLabel('615', '提交')}</span>
                                    </span>
                                </Button>
                            </span>,
                        ],
                    }}
                />

                <FeedBack ecId={`${this && this.props && this.props.ecId || ''}_FeedBack@plfogy`} dataSource={fblist} style={{ marginTop: "10px" }} />
            </div>
        </WeaSearchGroup>
    }
    saveFeedback = () => {
        this.store.addPlanExchange();
        this.store.setValue('feedback', '');
    };
    formatFblist = list => {
        let result = [];
        list.map(v => {
            result.push({
                operatedate: v.datetime,
                hrmid: v.hrmid,
                hrmname: v.hrmname,
                content: v.content,
            });
        });
        return result;
    };

    feedbackRichTextChange = v => {
        this.store.setValue('feedback', v);
    };
}
